'use client';

import Title from "antd/es/typography/Title";
import { Divider, Flex, Button, message } from "antd";
import Link from "next/link";
import { listQuestionBankVoByPageUsingPost } from "@/api/questionBankController";
import { listQuestionVoByPageUsingPost } from "@/api/questionController";
import QuestionBankList from "@/components/QuestionBankList";
import QuestionList from "@/components/QuestionList";
import "./index.css";
import { PageContainer } from "@ant-design/pro-components";
import { Card, Col, Row } from "antd";
import React from "react";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";
import { getRecommendQuestionsUsingGet } from "@/api/questionRecommendController";
import { useRouter, useSearchParams } from "next/navigation";

/**
 * 主页
 * @constructor
 */
export default function HomePage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  // 获取登录用户信息
  const loginUser = useSelector((state: RootState) => state.loginUser);
  // 题库推荐列表
  const [questionBankList, setQuestionBankList] = React.useState<API.QuestionBankVO[]>([]);
  // 最新题目列表
  const [questionList, setQuestionList] = React.useState<API.QuestionVO[]>([]);
  // 推荐题目列表
  const [recommendQuestionList, setRecommendQuestionList] = React.useState<API.QuestionVO[]>([]);

  // 处理 URL 中的 token
  React.useEffect(() => {
    const token = searchParams.get('token');
    if (token) {
      // 保存 token 到 localStorage
      localStorage.setItem('token', token);
      // 清除 URL 中的 token 参数
      router.replace('/');
    }
  }, [searchParams, router]);

  // 获取题库推荐列表
  const loadQuestionBankList = async () => {
    try {
      const res = await listQuestionBankVoByPageUsingPost({
        current: 1,
        pageSize: 8,
        sortField: "createTime",
        sortOrder: "descend",
      });
      setQuestionBankList(res.data?.records ?? []);
    } catch (e: any) {
      message.error("获取题库列表失败，" + e.message);
    }
  };

  // 获取最新题目列表
  const loadQuestionList = async () => {
    try {
      const res = await listQuestionVoByPageUsingPost({
        current: 1,
        pageSize: 8,
        sortField: "createTime",
        sortOrder: "descend",
      });
      setQuestionList(res.data?.records ?? []);
    } catch (e: any) {
      message.error("获取题目列表失败，" + e.message);
    }
  };

  // 获取推荐题目列表
  const loadRecommendQuestionList = async () => {
    if (!loginUser?.id) {
      return;
    }
    try {
      const res = await getRecommendQuestionsUsingGet({
        limit: 8,
        userId: loginUser.id
      });
      if (res.data) {
        setRecommendQuestionList(res.data as API.QuestionVO[]);
      }
    } catch (e: any) {
      message.error("获取推荐题目失败，" + e.message);
    }
  };

  React.useEffect(() => {
    loadQuestionBankList();
    loadQuestionList();
  }, []);

  // 当 loginUser 变化时，重新加载推荐题目
  React.useEffect(() => {
    if (loginUser?.id) {
      loadRecommendQuestionList();
    }
  }, [loginUser]);

  return (
    <PageContainer>
      <div id="homePage" className="max-width-content">
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Card title="题库推荐" variant={"borderless"}>
              <QuestionBankList questionBankList={questionBankList} />
            </Card>
          </Col>
          <Col span={24}>
            <Card title="为你推荐" variant={"borderless"}>
              <QuestionList questionList={recommendQuestionList} />
            </Card>
          </Col>
        </Row>
      </div>
    </PageContainer>
  );
}
